import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

const List<String> defautImages = [
  'http://ww3.sinaimg.cn/large/006y8mN6ly1g6e2tdgve1j30ku0bsn75.jpg',
  'http://ww3.sinaimg.cn/large/006y8mN6ly1g6e2whp87sj30ku0bstec.jpg',
  'http://ww3.sinaimg.cn/large/006y8mN6ly1g6e2tl1v3bj30ku0bs77z.jpg',
];
// 图片宽750px，高424px；
var imageWidth = 750.0;
var imageHeight = 424.0;
var imageWidthHeightRatio = imageWidth / imageHeight;

class CommonImagePicker extends StatefulWidget {
  final ValueChanged<List<File>> onChange;
  CommonImagePicker({Key key, this.onChange}) : super(key: key);

  @override
  _CommonImagePickerState createState() => _CommonImagePickerState();
}

class _CommonImagePickerState extends State<CommonImagePicker> {
  List<File> fileList = [];
  final picker = ImagePicker();
  _getImage() async {
    final pickedFile = await picker.getImage(source: ImageSource.gallery);
    if (pickedFile == null) return;
    setState(() {
      fileList = fileList..add(File(pickedFile.path));
    });
    if (widget.onChange != null) {
      widget.onChange(fileList);
    }
  }

  @override
  Widget build(BuildContext context) {
    var width = (MediaQuery.of(context).size.width - 10 * 4) / 3;
    var height = width / imageWidthHeightRatio;

    Widget addButton = GestureDetector(
      onTap: () {
        _getImage();
      },
      behavior: HitTestBehavior.translucent,
      child: Container(
        width: width,
        height: height,
        color: Colors.grey,
        alignment: Alignment.center,
        child: Text(
          '+',
          style: TextStyle(fontSize: 40, fontWeight: FontWeight.w100),
        ),
      ),
    );

    Widget wrapper(File imageFile) {
      return Stack(
        overflow: Overflow.visible,
        children: [
          Image.file(imageFile,
              width: width, height: height, fit: BoxFit.cover),
          Positioned(
            right: -20,
            top: -20,
            child: IconButton(
                icon: Icon(Icons.delete_forever, color: Colors.red),
                onPressed: () {
                  setState(() {
                    fileList = fileList..remove(imageFile);
                  });
                  if (widget.onChange != null) {
                    widget.onChange(fileList);
                  }
                }),
          )
        ],
      );
    }

    List<Widget> list = fileList.map((e) => wrapper(e)).toList()
      ..add(addButton);

    return Container(
      padding: EdgeInsets.all(10.0),
      child: Wrap(
        children: list,
        spacing: 10,
        runSpacing: 10,
      ),
    );
  }
}
